//
//  AsyncViewController.m
//  TestIos
//
//  Created by Liyadong on 2024/3/21.
//  Copyright © 2024 Liyadong. All rights reserved.
//

#import "AsyncViewController.h"
#import "Masonry.h"

@interface AsyncViewController ()

@property (nonatomic, strong) UIButton *demoButton;

@end

@implementation AsyncViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.demoButton.frame = CGRectMake(20, 100, 150, 50);
    [self.view addSubview:self.demoButton];
}

- (void)demoButtonClicked {
//    [self syncMain];
    
    [self test];
}


- (void)syncMain {
    dispatch_queue_t globalQueue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);

    // 并发执行多个读操作
    dispatch_async(globalQueue, ^{
        NSLog(@"Read Task 1");
    });

    dispatch_async(globalQueue, ^{
        NSLog(@"Read Task 2");
    });

    // 栅栏任务（写操作），会等待前面的读操作完成
    dispatch_barrier_async(globalQueue, ^{
        NSLog(@"Write Task (Barrier)"); // 独占队列
    });

    // 栅栏任务完成后，继续并发执行
    dispatch_async(globalQueue, ^{
        NSLog(@"Read Task 3");
    });
}

- (void)test {

 
    // 创建信号量，初始值为3（最大并发数）
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(3);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     
    for (int i = 0; i < 10; i++) {
        dispatch_async(queue, ^{
            // 等待信号量（若计数器>0则继续，否则阻塞）
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            
            // 模拟耗时任务（如网络请求）
            NSLog(@"Task %d started on thread: %@", i, [NSThread currentThread]);
            [NSThread sleepForTimeInterval:5.0];
            NSLog(@"Task %d finished", i);
            
            // 释放信号量（计数器+1）
            dispatch_semaphore_signal(semaphore);
        });
    }
    
    
}


 

#pragma mark - Actions
 

#pragma mark - Lazy Loading

- (UIButton *)demoButton {
    if (!_demoButton) {
        _demoButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_demoButton setTitle:@"多线程测试按钮" forState:UIControlStateNormal];
        [_demoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _demoButton.backgroundColor = [UIColor systemBlueColor];
        _demoButton.layer.cornerRadius = 8;
        [_demoButton addTarget:self action:@selector(demoButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _demoButton;
}

@end 
